package com.xframe.common.core.service.command;

import com.xframe.common.core.constant.ErrorConstant;
import com.xframe.domain.repository.SysModelRepository;
import com.xframe.domain.role.IUserCredentials;
import com.xframe.domain.sys.SysModel;
import com.xframe.domain.CommandModel;
import com.xframe.common.core.exception.BusinessException;
import com.xframe.domain.ModelRepositoryFactory;
import com.xframe.xdal.core.exception.DalFrameException;
import com.xframe.xdal.core.model.mapping.ITableInfo;
import com.xframe.xdal.core.model.mapping.TableInfoBuilder;
import com.xframe.xdal.core.util.StringUtil;

import java.util.Map;

public class RegBeanToModelProc extends BaseCommand {


    @Override
    public Object ProcCommand(CommandModel requestArgs, IUserCredentials userCredentials) {
        try {
            Map<String,Object> dto = requestArgs.getCommandBodyByMap();
            if (dto.get("modelCode") == null || StringUtil.isEmpty(dto.get("modelCode").toString())) {
                throw new BusinessException(com.xframe.common.core.dto.ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel regModel = new SysModel();
            regModel.setModelCode(dto.get("modelCode").toString());
            regModel.setClassName(dto.get("modelCode").toString());
            regModel.setModelName(dto.get("modelName") == null ? null:dto.get("modelName").toString());
            if (StringUtil.isEmpty(regModel.getModelCode())) {
                throw new BusinessException(com.xframe.common.core.dto.ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            if (StringUtil.isEmpty(regModel.getModelName())) {
                ITableInfo tableInfo = TableInfoBuilder.BuildTableInfoByAnnotation(regModel.getModelDataType());
                regModel.setModelName(tableInfo.getLabel());
            }
            SysModelRepository sysBaseRepository = ModelRepositoryFactory.builder(SysModel.class);
            this.execRepository(sysBaseRepository, "regBeanToModel", regModel.getModelCode(), regModel.getModelName(), userCredentials);
            return 0;
        } catch (BusinessException businessException) {
            throw businessException;
        } catch (DalFrameException exception) {
            throw new BusinessException(exception.getCode(), exception.getMessage());
        } catch (Exception exception) {
            throw new BusinessException(com.xframe.common.core.dto.ErrorCode.INTERNAL_SERVER_ERROR, exception.getMessage());
        }

    }

    @Override
    public String getBeanName() {
        return "RegBeanToModel";
    }
}
